package com.example.saifly.login;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.common.Activity;
import com.example.common.Application.MyApplication;
import com.example.common.Retrofit.RetrofitHelper;
import com.example.common.Util.RegxUtil;
import com.example.saifly.R;
import com.example.saifly.mainPage.MainPageActivity;
import com.kaopiz.kprogresshud.KProgressHUD;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;

public class LoginActivity extends Activity {

    private EditText etPhone;
    private EditText etVerifyCode;
    private Button btLogin,btReceiveAgain;
    private boolean firstClick=true;
    private ConstraintLayout clVerify;
    private int time=5;
    private TimeCount timeCount;
    private String phoneNumber;
    private KProgressHUD hud;


    private SharedPreferences sharedPreferences;

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_login_phonenumber;
    }

    @Override
    protected void init() {
        super.init();

        etPhone=findViewById(R.id.login_phone_number);
        etVerifyCode=findViewById(R.id.login_verify_code);
        btLogin=findViewById(R.id.login_next);
        clVerify=findViewById(R.id.login_layout_verify);
        btReceiveAgain=findViewById(R.id.login_reget_verify_code);

        //初始化全局变量，稍后用于存入uid
        sharedPreferences= MyApplication.getContext().getSharedPreferences("config", Context.MODE_PRIVATE);

        timeCount = new TimeCount(60000,1000,btReceiveAgain);


        initCommit();
    }

    private void initCommit(){
        btLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("registerhaha", "onClick: pushButton"+firstClick);
                //第一次提交
                if(firstClick){
                    phoneNumber=etPhone.getText().toString().trim();
                    if(RegxUtil.isPhone(phoneNumber)){
                        btLogin.setText("提交");
                        firstClick=!firstClick;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                clVerify.setVisibility(View.VISIBLE);
                            }
                        });
                        Log.d("registerhaha", "onClick: runOnUiSuccess");
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Log.d("registerhaha", "run:readyToGetVerifyCode ");
                                //显示动画
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
//                                        hud=KProgressHUD.create(LoginActivity.this)
//                                                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
//                                                .setLabel("Please wait")
//                                                .setAnimationSpeed(2)
//                                                .setDimAmount(0.5f);
                                    }
                                });
                                getVerifyCode(phoneNumber);
                            }
                        }).start();

                    }
                    else{
                        Toast.makeText(LoginActivity.this,"请输入正确的手机号",Toast.LENGTH_SHORT).show();
                    }
                }
                else{
                    String inputVerifyCode=etVerifyCode.getText().toString().trim();
                    //开始loading
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            hud.show();
                        }
                    });
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            sendVerifyRequest(phoneNumber,inputVerifyCode);
                        }
                    }).start();

                }
            }
        });

        btReceiveAgain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        getVerifyCodeAgain(phoneNumber);
                    }
                }).start();
            }
        });
    }




    /**
     * 服务器发请求验证手机号和验证码
     * @param verifyCode
     */
    private boolean checkVerifyCode(String verifyCode){
        return true;
    }

//    验证登录
    private void sendVerifyRequest(String phoneNumber,String verifyCode){
        //如果成功那么跳转，如果失败提示输入错误
        //检查验证码
//        Retrofit retrofit=new Retrofit.Builder()
//                .baseUrl(getString(R.string.base_url))
//                .client(client)
//                .addConverterFactory(GsonConverterFactory.create())
//                .build();

        RetrofitHelper retrofitHelper=new RetrofitHelper();
        Retrofit retrofit=retrofitHelper.getRetrofit();

        ApiGetVerifyCode apiGetVerifyCode=retrofit.create(ApiGetVerifyCode.class);

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("code",verifyCode);
        Log.d("registerhaha", "sendVerifyRequest: "+jsonObject);

        Call<ResponseBody> call=apiGetVerifyCode.registerVerifyVerify(jsonObject);
        final Response<ResponseBody> response;
        Log.d("registerhaha", "sendVerifyRequest: enteringhaha");
        try {
            response = call.execute();
            if(response.body() != null){
                JSONObject result=JSON.parseObject(response.body().string());
                if(result.getInteger("code")!=null&&result.getInteger("code")==1){
                    String identity=result.getJSONObject("result").getString("identity");
                    if(identity.equals("register")){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                startActivity(new Intent(LoginActivity.this,IndexActivity.class).putExtra("uid",phoneNumber));
                            }
                        });
                    }
                    else{
                        //患者或家属情况，存入patientinfo和identity
                        PatientInfomation patientInfomation=JSON.parseObject(result.getJSONObject("result").getString("patientInfomation"),PatientInfomation.class);
//                        Log.d("loginfinal", "sendVerifyRequest: "+patientInfomation.toString());
//                        if(identity.equals("family")){
//                            new Thread(new Runnable() {
//                                @Override
//                                public void run() {
////                                    getPid(phoneNumber);
//                                }
//                            }).start();
//                        }

                        //存入全局变量 patienInfomation
                        sharedPreferences.edit()
                                .putString("uid",patientInfomation.getPatientPhone())
                                .putString("nickname",patientInfomation.getPatientName())
                                .putString("contactPhone",patientInfomation.getPatientContactPhone())
                                .putString("sex",patientInfomation.getPatientSex())
                                .putString("portrait",patientInfomation.getPatientAvatar())
                                .putString("identity",identity)
                                .putString("fid",phoneNumber)
                                .apply();

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Intent intent=new Intent(LoginActivity.this, MainPageActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                            }
                        });
                    }
                }
                else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(LoginActivity.this, "验证码输入错误", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        } catch (IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(LoginActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }
    }


    private interface ApiGetVerifyCode{
        //        //获取验证码
        @Headers({"Content-Type:application/json"})
        @POST("/login/send")
        Call<ResponseBody> registerGetVerify(@Body JSONObject jsonObject);

        @Headers({"Content-Type:application/json"})
        @POST("/login/check")
        Call<ResponseBody> registerVerifyVerify(@Body JSONObject jsonObject);

        @Headers({"Content-Type:application/json"})
        @POST("/arrange/getPatientPhone")
        Call<ResponseBody> getpid(@Body JSONObject jsonObject);

    }

    /**
     * 服务器发请求获取验证码
     * @param phoneNumber
     */
    private void getVerifyCode(String phoneNumber) {
        RetrofitHelper retrofitHelper=new RetrofitHelper();
        Retrofit retrofit=retrofitHelper.getFirstRetrofit();

        ApiGetVerifyCode apiGetVerifyCode=retrofit.create(ApiGetVerifyCode.class);

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("phone",phoneNumber);
        Call<ResponseBody> call=apiGetVerifyCode.registerGetVerify(jsonObject);
        final Response<ResponseBody> response;
        try {
            response = call.execute();
            if(response.body() != null){
                JSONObject result=JSON.parseObject(response.body().string());
                if(result.getInteger("code")!=null&&result.getInteger("code")==1){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(LoginActivity.this,"验证码已发送至" + phoneNumber,Toast.LENGTH_SHORT).show();
                            //开始倒计时
                            timeCount.start();
//                    hud.dismiss();
                        }
                    });
                }
                else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(LoginActivity.this, "网络出现异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        } catch (IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(LoginActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }

    }

    private void getVerifyCodeAgain(String phoneNumber) {
        RetrofitHelper retrofitHelper=new RetrofitHelper();
        Retrofit retrofit=retrofitHelper.getRetrofit();

        ApiGetVerifyCode apiGetVerifyCode=retrofit.create(ApiGetVerifyCode.class);

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("phone",phoneNumber);
        Call<ResponseBody> call=apiGetVerifyCode.registerGetVerify(jsonObject);
        final Response<ResponseBody> response;
        try {
            response = call.execute();
            if(response.body() != null){
                JSONObject result=JSON.parseObject(response.body().string());
                Log.d("loginfinal", "getVerifyCodeAgain: "+result.toString());
                if(result.getInteger("code")!=null&&result.getInteger("code")==1){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(LoginActivity.this,"验证码已发送至" + phoneNumber,Toast.LENGTH_SHORT).show();
                            //开始倒计时
                            timeCount.start();
//                    hud.dismiss();
                        }
                    });
                }
                else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(LoginActivity.this, "网络出现异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        } catch (IOException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(LoginActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }

    }


    private void getPid(String phoneNumber){
        RetrofitHelper retrofitHelper=new RetrofitHelper();
        Retrofit retrofit=retrofitHelper.getRetrofit();

        ApiGetVerifyCode apiGetVerifyCode=retrofit.create(ApiGetVerifyCode.class);

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("familyPhone",phoneNumber);

        Call<ResponseBody> call=apiGetVerifyCode.registerGetVerify(jsonObject);
        final Response<ResponseBody> response;

        try{
            response=call.execute();
            if(response.body()!=null){
                JSONObject result=JSON.parseObject(response.body().string());
                Log.d("loginFInal", "getPid: "+result.getString("result"));
                sharedPreferences.edit().putString("pid",result.getString("result")).apply();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //倒计时类
    class TimeCount extends CountDownTimer {
        private Button bt;
        public TimeCount(long msInFuture, long countDownInterval, Button bt) {
            super(msInFuture,countDownInterval);
            this.bt = bt;
        }

        @Override
        public void onTick(long msUntilFinished) {
            bt.setEnabled(false);
            bt.setText("重新获取("+msUntilFinished/1000 + ")秒");//设置倒计时时间
        }

        @Override
        public void onFinish() {
            bt.setEnabled(true);
            bt.setText("重新获取");
        }
    }
}
